package geektime.concurrent.part2.concurrencycontrol;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreDemo {

    private Semaphore semaphore = new Semaphore(3);

    public static void main(String[] args) throws InterruptedException {
        SemaphoreDemo semaphoreDemo = new SemaphoreDemo();
        semaphoreDemo.new WorkThread("Thread1").start();
        semaphoreDemo.new WorkThread("Thread2").start();
//        TimeUnit.SECONDS.sleep(2);
//        System.out.println(semaphoreDemo.semaphore.availablePermits());
        semaphoreDemo.new WorkThread("Thread3").start();
        semaphoreDemo.new WorkThread("Thread4").start();
    }

    class WorkThread extends Thread {

        private String name;

        public WorkThread(String name) {
            setName(name);
        }

        @Override
        public void run() {
            System.out.printf("[%s]已创建\n", Thread.currentThread().getName());
            try {
                semaphore.acquire();
                System.out.printf("[%s]获取到了semaphore执行权\n", Thread.currentThread().getName());
                // 模拟某个动作执行需要5秒钟
                TimeUnit.SECONDS.sleep(5);
                // 执行完毕后释放semaphore执行权
                semaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
